﻿using SampleWebApp.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;

namespace SampleWebApp.Controllers
{
    //***************************************************************
    //*Uses Session to simulate adding and removing from a data store
    //***************************************************************

    public class PersonController : ApiController
    {
        // GET api/person
        public IEnumerable<Person> Get()
        {
            return (IEnumerable<Person>)HttpContext.Current.Session["people"] ?? new List<Person>();
        }

        // POST api/person
        public void Post([FromBody]Person value)
        {
            if (!ModelState.IsValid)
            {
                throw new ArgumentException("Invalid model state.");
            }

            if(HttpContext.Current.Session["people"] == null)
            {
                HttpContext.Current.Session["people"] = new List<Person>();
            }

            ((List<Person>)HttpContext.Current.Session["people"]).Add(value); 
        }

        // DELETE api/person/5
        public void Delete(string email)
        {
            if (HttpContext.Current.Session["people"] == null)
            {
                HttpContext.Current.Session["people"] = new List<Person>();
            }

            var people = ((List<Person>)HttpContext.Current.Session["people"]);

            people.RemoveAll(p => p.Email.ToLower() == email.ToLower());
        }
    }
}
